//
//  NetworkRequest.swift
//  HHSwift
//
//  Created by 华宏 on 2019/1/31.
//  Copyright © 2019年 huahong. All rights reserved.
//

import Foundation
import Alamofire
import RxSwift

/* 为闭包声明别名 */
typealias Success = (_ response:[String:AnyObject]) -> ()
typealias Failure = (_ response:[String:AnyObject]) -> ()


//final:这个类或方法不希望被继承和重写
//尝试不继承NSObject
final class NetworkRequest: NSObject {
    
    static let shareNetworkRequest = NetworkRequest()
    let disposeBag = DisposeBag()
    
    /// 使用 Alamofire 向网络发起请求
    ///
    /// - Parameters:
    ///   - urlStr: url字符串
    ///   - params: 请求参数
    ///   - method:
    ///   - success: 返回成功结果
    ///   - failure: 返回失败结果
    func request(urlStr:String,params:[String:Any]?,method:HTTPMethod,success:@escaping(Success),failure:@escaping(Failure))  {
        
        let headers:HTTPHeaders =
            [
            "Accept": "application/json",
        //            "Accept": "text/javascript",
        //            "Accept": "text/html",
        //            "Accept": "text/plain"
           ]
        
//        let headers:HTTPHeaders = ["Content-type":"application/x-www-form-urlencoded",
//              "Accept":"application/json",
//              "systemtype":"ios",
//              "channel":"00",
//              "Authorization":""]
        
        Alamofire.request(urlStr, method: method, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response:DataResponse<Any>) in
            
            switch(response.result){
            case .success(_):
               //当响应成功是，使用临时变量value接受服务器返回的信息并判断是否为[String: AnyObject]类型 如果是那么将其传给其定义方法中的success
                if let value = response.result.value as? [String:AnyObject]{
//                    let json = JSON(value)
                    success(value)
//                    print("json ======\n", json)
                    
                }
                
                break
            case .failure(let error):
                failure(error as! [String:AnyObject])
                print("error ======\n", error)
                
            }
        }
    }
    
    
    // MARK: 图片上传
    func upLoadImageRequest(urlStr:String,params:[String:String],data:[Data],name:[String],success:@escaping(Success),failure:@escaping(Failure)) {
        
        let headers = ["content-type":"multipart/form-data"]
        
        Alamofire.upload(multipartFormData: { (MultipartFormData) in
            
            let userId = params["userId"]
            MultipartFormData.append((userId?.data(using: String.Encoding.utf8))!, withName: "userId")
            for i in 0..<data.count{
                MultipartFormData.append(data[i], withName: "appPhoto", fileName: name[i], mimeType: "image/png")
            }
            
            
        }, usingThreshold: SessionManager.multipartFormDataEncodingMemoryThreshold, to: urlStr, method: HTTPMethod.post, headers: headers) { encodingResult in
            
            switch encodingResult{
            case .success(let upload,_,_):
                upload.responseJSON(completionHandler: { (response) in
                    if let value = response.result.value as? [String :AnyObject]{
//                        let json = JSON(value)
                        success(value)
//                        print(json)
                        
                    }
                })
                break
                
            case .failure(let error):
                print(error)
                failure(error as! [String :AnyObject])
            }
        }
    }
 
    
    //MARK:https证书验证
    func verifacationCertificate() {
        let manager = SessionManager.default
        manager.delegate.sessionDidReceiveChallenge = {session,challenge in
            
            var disposion:URLSession.AuthChallengeDisposition = .performDefaultHandling
            var credenial:URLCredential?
            if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
                
                disposion = URLSession.AuthChallengeDisposition.useCredential
                credenial = URLCredential.init(trust: challenge.protectionSpace.serverTrust!)
            }else
            {
                if challenge.previousFailureCount > 0 {
                    disposion = .cancelAuthenticationChallenge
                }else
                {
                    credenial = manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
                    
                    if credenial != nil {
                        disposion = .useCredential
                    }
                    
                }
            }
            
            
            return (disposion,credenial)
        }
        
    }
    

    
    func rxRequest() {
           let url = URL(string: "http://58.215.175.244:8090/thirdprovider/datacenter/area/findAllAreaJsonTree")
           var request = URLRequest(url: url!)
           request.httpMethod = "POST"
         let param = ["userId":""]
        let httpBody = try! JSONSerialization.data(withJSONObject: param, options: .fragmentsAllowed)
        
        request.httpBody = httpBody
        
           URLSession.shared.rx.json(request: request)
               .subscribe(onNext: { (data) in
               print("data === \(data)")
           }, onError: { (error) in
               print("error === \(error)")
           }).disposed(by: disposeBag)
       }
    
    func systemPost() {
     
            let session = URLSession(configuration: .default)
            var request = URLRequest(url: URL(string: "http://58.215.175.244:8090/thirdprovider/datacenter/area/findAllAreaJsonTree")!)
            request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
            request.httpMethod = "POST"
            // 设置要post的内容，字典格式
             let param = ["userId":""]
            let httpBody = try! JSONSerialization.data(withJSONObject: param, options: .fragmentsAllowed)
            request.httpBody = httpBody
        
    
            let task = session.dataTask(with: request) {(data, response, error) in
                do{
                    //              将二进制数据转换为字典对象
                    if let jsonObj = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions()) as? Dictionary<String,Any>
                    {
                        print(jsonObj)
                       
                    }
                } catch{
                    print("Error.")
                   
                    
                }
            }
            task.resume()
    
    }
}
